package DB;

import java.util.ArrayList;
import java.util.Date;

import org.lightcouch.CouchDbClient;

import Utility.Base64;

import com.google.gson.JsonObject;


public class GroupTableDB {
	private CouchDbClient dbClient;
	public static final String IDCOL = "_id";
	public static final String NAMECOL = "name";
	public static final String OWNERCOL = "ownerid";
	public static final String GROUPS = "groups";

	public GroupTableDB() {
		dbClient = new CouchDbClient(GROUPS, true, "http", "127.0.0.1", 5984,
				null, null);
	}

	public String createGroup(String userID, String name) {
		JsonObject object = new JsonObject();
		String id = String.valueOf(new Date().getTime() + new Date().getTime());
		object.addProperty(IDCOL, id);
		object.addProperty(NAMECOL, name);
		object.addProperty(OWNERCOL, userID);
		// save the message
		dbClient.save(object);
		GroupAndUsersTableDB groupAndUsersTableDB = new GroupAndUsersTableDB();
		groupAndUsersTableDB.createGroupAndUsers(userID, id);
		return "success";
	}

	public String deleteGroup(String groupID) {
		JsonObject json = dbClient.find(JsonObject.class, groupID);
		dbClient.remove(json);
		
		GroupAndUsersTableDB groupAndUsersTableDB = new GroupAndUsersTableDB();
		groupAndUsersTableDB.deleteGroupAndUsersByGroup(groupID);
		ChatTableDB chatTableDB = new ChatTableDB();
		chatTableDB.deleteChatByGroup(groupID);
		
		return "success";
	}
	
	public String deleteGroupByOwner(String userID){
		ArrayList<JsonObject> allDocs = (ArrayList<JsonObject>) dbClient.view("_all_docs").includeDocs(true).query(JsonObject.class);
		for(JsonObject json: allDocs){
			if(json.get(OWNERCOL).getAsString().equals(userID)){
				deleteGroup(json.get(IDCOL).getAsString());
			}
		}
		return "success";
	}

	public ArrayList<JsonObject> seletGroups() {
		return new ArrayList<JsonObject>();
	}

	/**
	 * select all groups belongs to a user
	 * @param userID
	 * @return
	 */
	public ArrayList<JsonObject> seletGroupsByUser(String userID) {
		ArrayList<JsonObject> result = new ArrayList<JsonObject>();
		GroupAndUsersTableDB groupAndUsersTableDB = new GroupAndUsersTableDB();
		ArrayList<JsonObject> groupIDS = groupAndUsersTableDB.selectGroupAndUserByUser(userID);
		
		for(JsonObject groupID: groupIDS){
			result.add(dbClient.find(JsonObject.class, groupID.get(GroupAndUsersTableDB.GROUPFK).getAsString()));
		}
		return result;
	}
	
	public JsonObject selectGroupByID(String groupID){
		JsonObject json = dbClient.find(JsonObject.class, groupID);
		return json;
	}

}
